<?php

class ReceiptsController extends Controller
{
	public function actionIndex($page = 1)
	{
		$rows = $this->getSearchResults($page);
		$pageSize = Yii::app()->params['receiptPageSize'];
		$reports = Yii::app()->db->createCommand("EXEC stp_GetAllActivedReports")->queryAll();
		$this->render('index',array(
		'rows'=>$rows,
		'page'=>$page,
		'limit'=>$pageSize,
		'totalItem'=>isset($rows[0]['TotalCount'])?$rows[0]['TotalCount']:0,
		'reports'=>$reports
		));
	}
	private function getSearchResults($page=1)
	{
		$from = isset($_REQUEST['startDate'])?$_REQUEST['startDate']: date('Y-m-d G:i:s', PHP_INT_MAX + 1);
		$to = isset($_REQUEST['endDate'])?$_REQUEST['endDate']: date('Y-m-d G:i:s', PHP_INT_MAX);
		$attachedReceipt = isset($_REQUEST['attach'])?$_REQUEST['attach']:'UNATTACHED';
		$pageSize = Yii::app()->params['receiptPageSize'];
		$filterSelector = isset($_REQUEST['filter_selector'])?$_REQUEST['filter_selector']:'';
		$command  = Yii::app()->db->createCommand("EXEC stp_GetAllReceiptLimited :From, :To,:FilterSelector,:AttachedReceipt,:PageSize,:Page");
		$command->bindValue(':From',  $from, PDO::PARAM_STR);
		$command->bindValue('To',  $to, PDO::PARAM_STR);
		$command->bindValue(':FilterSelector', $filterSelector, PDO::PARAM_STR);
		$command->bindValue(':AttachedReceipt', $attachedReceipt, PDO::PARAM_STR);
	    $command->bindValue(':PageSize', $pageSize, PDO::PARAM_INT);	
	    $command->bindValue(':Page', $page, PDO::PARAM_INT);
		$rows = $command->queryAll();
		return $rows!=null?$rows:array();
	}
	/**
	 * 
	 * Execute to search the receipt by the searching condition
	 * @param int $page
	 */
	public function actionSearch($page=1)
	{
		$this->layout='//layouts/main';
		$pageSize = Yii::app()->params['receiptPageSize'];
		$rows = $this->getSearchResults($page);
		$this->render('search',array(
		'rows'=>$rows,
		'page'=>$page,
		'limit'=>$pageSize,
		'totalItem'=>isset($rows[0]['TotalCount'])?$rows[0]['TotalCount']:0
		));
	}
	/**
	 * 
	 * Delete receipt by check all
	 */
	public function actionDelete()
	{
		if(isset($_POST['deleteString']))
		{
			$deleteString = $_POST['deleteString'];
			$command  = Yii::app()->db->createCommand("EXEC stp_SetDeleteFlgReceipts '$deleteString'")->execute();
			
		}
	}
/**
	 * 
	 * Add receipts to report
	 */
	public function actionAddReceiptsToReport()
	{
		if(isset($_POST['receiptString']))
		{
			$receiptString = $_POST['receiptString'];
			$reportId = $_POST['reportId'];
			$command  = Yii::app()->db->createCommand("EXEC stp_AddReceiptsToReport '$receiptString','$reportId'")->execute();
		}
	}
	/**
	 * 
	 * Delete each receipts
	 */
	public function actionDeleteEach()
	{
	    if(isset($_POST['delete_id']))
		{
			$deleteId = $_POST['delete_id'];
			
			$command  = Yii::app()->db->createCommand("EXEC stp_SetDeleteFlgEachReceipt '$deleteId'")->execute();
		}
	}
	
	/**
	 * 
	 * This function return a json from an array
	 * @param $data
	 */
    private function renderJSON($data) {
		header('Content-type: application/json');
		echo CJSON::encode($data);

		foreach (Yii::app()->log->routes as $route) {
			if ($route instanceof CWebLogRoute) {
				$route -> enabled = false;
				// disable any weblogroutes
			}
		}
		Yii::app() -> end();
	}
	/**
	 * 
	 * This function is used for uploading a reciept file to server by ajax
	 */
    public function actionRecieptUpload()
    {
        $allowedExts = array("gif", "jpeg", "jpg", "png");
		$temp = explode(".", $_FILES["file"]["name"]);
		$extension = end($temp);
		$result = "";

		if ((($_FILES["file"]["type"] == "image/gif")
		|| ($_FILES["file"]["type"] == "image/jpeg")
		|| ($_FILES["file"]["type"] == "image/jpg")
		|| ($_FILES["file"]["type"] == "image/pjpeg")
		|| ($_FILES["file"]["type"] == "image/x-png")
		|| ($_FILES["file"]["type"] == "image/png"))
		&& ($_FILES["file"]["size"] < Yii::app()->params['receiptUploadSize'])
		&& in_array($extension, $allowedExts))
		  {
		  	 
			  if ($_FILES["file"]["error"] <= 0)
			    {
				    
				    if (!file_exists(Yii::app()->params['receiptUploadDir'].'/' . $_FILES["file"]["name"]))
				      {
				      	
				      	$fileName = uniqid().'_'.$_FILES["file"]["name"];
				        move_uploaded_file($_FILES["file"]["tmp_name"],
				        Yii::app()->params['receiptUploadDir'].'/' . $fileName);
				        $url = Yii::app()->baseUrl.'/upload/receipts/'.$fileName;
				        $receipt = new Receipt();
				        $receipt->Url = $url;
				        $receipt->CreateAt = date('Y-m-d H:i:s');
				        $receipt->Enable = true;
				        $receipt->DeleteFlg = false;
				        $receipt->Submitted = false;
				        $receipt->insert();
				        $result='<div class="receipt_wrapper receipt_notSelected" id="receipt_'.$receipt->ReceiptId.'">
								<div class="receipts_selector_container"><input type="checkbox" class="receipts_selector_checkbox" id="receipts_selector_18980378"></div>
								<div class="receipt OPEN attached"><span class="receiptID" value="18980378"><span class="transactionID"></span><a class="fancy" href="'.$url.'"><img class="receiptimage" id="receiptimg_'.$receipt->ReceiptId.'"  src="'.$url.'"></a></span>
								<div style="display: none;" class="scanStatus hidden"></div>
								<div class="receipt_caption">
								<div class="receipt_actions">
								<div class="button delete delete_receipt_button"><a href="#" class="iconButton"></a></div>
								<div class="button download_receipt_button"><a href="'.$url.'" target="_blank" class="iconButton"></a></div>
								</div>
								</div>
								</div>
								<ul class="expenseInfo pairs reported  ">
								<li>
								<p>Date:</p>
								<span>'.$receipt->CreateAt.'</span></li>
								</ul>
								</div>';
				      }
			    }
		  }

		echo $result;
    }
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}